<template>
  <div class="config">
      <el-col :span="12">
        <el-card class="box-card box-left">
          <el-row class="header">
            <el-button type="primary" @click="alertShow('company')" :disabled="addAlert">新建</el-button>
          </el-row>
          <el-row>
            <el-card v-if="!companyArr.length" class="content-card" style="height: 150px;line-height: 150px;text-align: center;color: #666;">
              请新建一个公司
            </el-card>
						<div v-else v-for="(item,index) in companyArr" :key="index">
							<p class="cr-time">
								<span>创建时间：{{item.create_time | parseTime('{y}-{m}-{d}')}}</span>
							</p>
							<el-card  class="content-card" >
								<div @click="showSection(item.id)">
									<el-row>
										<span style="width: 75px;display: inline-block;float: left;">公司名称：</span>
										<span style="width: 65%;display: inline-block;">{{item.company_name}}</span>
										<span class="action">
                    <el-dropdown @command="companyCommand">
                      <span class="el-dropdown-link">
                        操作<i class="el-icon-arrow-down el-icon--right"></i>
                      </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item :command="'a' + item.id">编辑</el-dropdown-item>
                        <el-dropdown-item :command="'b' + item.id">删除</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </span>
									</el-row>
									<el-row>
										<span style="width: 75px;display: inline-block;float: left;">所在地址：</span>
										<span style="width: 65%;display: inline-block;">{{item.address_text}}</span>
									</el-row>
									<el-row>
										<span>负责人：</span>
										<span v-if="item.company_leader_text">{{item.company_leader_text}}</span>
										<span v-else>无</span>
									</el-row>
									<el-row>
										<span>员工数：</span>
										<span>{{item.employee_num}}</span>
									</el-row>
								</div>
							</el-card>
						</div>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="12" v-if="sectionShow">
        <el-card class="box-card box-right">
          <el-row class="card-header header">
            <el-button type="primary" @click="alertShow('section')" :disabled="addAlert">新建</el-button>
          </el-row>
          <el-row>
            <el-card v-if="!sectionArr.length" class="content-card" style="height: 150px;line-height: 150px;text-align: center;color: #666;">
              请新建一个部门
            </el-card>
						<div v-else v-for="(item, index) in sectionArr" :key="index">
							<p class="cr-time">
								<span>创建时间：{{item.create_time | parseTime('{y}-{m}-{d}')}}</span>
							</p>
							<el-card  class="content-card" >
								<div>
									<el-row>
										<span>部门名称：</span>
										<span>{{item.department_name}}</span>
										<span class="action">
                    <el-dropdown @command="sectioneCommand">
                      <span class="el-dropdown-link">
                        操作<i class="el-icon-arrow-down el-icon--right"></i>
                      </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item :command="'a' + item.id">编辑</el-dropdown-item>
                        <el-dropdown-item :command="'b' + item.id">删除</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </span>

									</el-row>
									<el-row>
										<span>负责人：</span>
										<span v-if="item.department_leader_text">{{item.department_leader_text}}</span>
										<span v-else>无</span>
									</el-row>
									<el-row>
										<span>员工数：</span>
										<span>{{item.employee_num}}</span>
									</el-row>
								</div>
							</el-card>
						</div>
          </el-row>
        </el-card>
      </el-col>
      <!-- 添加新公司 -->
      <el-col :span="10"  class="alert-card" style="padding: 0;" v-if="addAlert">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="left">
          <el-card class="setHeight">
            <el-row class="card_header">
              <span>{{alertTitle}}</span>
              <el-col :span="16" class="card_header_btn">
                <el-button type="primary" @click="saveBtn">保存</el-button>
                <el-button @click="cancel">取消</el-button>
              </el-col>
            </el-row>
            <el-row class="item">
              <p>基础信息</p>
              <div v-if="companyFrom">
                <el-col :span="14">
                  <el-form-item label="公司名称" prop="cname">
                    <el-input v-model="form.cname" placeholder="请输入公司名称"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="14">
                  <el-form-item label="公司简称" prop="simple">
                    <el-input v-model="form.simple" placeholder="请输入公司简称"></el-input>
                    <span class="describe">2-4位英文</span>
                  </el-form-item>
                </el-col>
                <el-col class="address">
                  <el-form-item label="所在地址" prop="address">
                      <el-col :span="8">
                        <el-select v-model="form.address.prov" placeholder="省" @change="getCityList(form.address.prov)">
                          <el-option
                            v-for="item in city.prov"
                            :key="item.id"
                            :label="item.class_name"
                            :value="item.id">
                          </el-option>
                        </el-select>
                      </el-col>
                      <el-col :span="8">
                        <el-select v-model="form.address.city" placeholder="市" @change="getCountyList(form.address.city)">
                          <el-option
                            v-for="item in city.city"
                            :key="item.id"
                            :label="item.class_name"
                            :value="item.id">
                          </el-option>
                        </el-select>
                      </el-col>
                      <el-col :span="8">
                        <el-select v-model="form.address.county" placeholder="区">
                          <el-option
                            v-for="item in city.county"
                            :key="item.id"
                            :label="item.class_name"
                            :value="item.id">
                          </el-option>
                        </el-select>
                      </el-col>
                  </el-form-item>
                </el-col>
                <el-col :span="14" style="margin-top:-25px;">
                  <el-form-item label="" prop="detail">
                    <el-input v-model="form.detail" placeholder="请输入详细地址"></el-input>
                  </el-form-item>
                </el-col>
              </div>
              <div v-if="sectionFrom">
                <el-col :span="14">
                  <el-form-item label="部门名称" prop="sname">
                    <el-input v-model="form.sname" placeholder="请输入部门名称"></el-input>
                  </el-form-item>
                </el-col>
              </div>
              <el-col :span="14">
                <el-form-item label="负责人" prop="manage">
                  <el-select
                    v-model="form.manage"
                    filterable
                    remote
                    clearable
                    reserve-keyword
                    placeholder="请输入负责人"
                    :remote-method="remoteMethod"
                    :loading="selectLoading">
                    <el-option
                      v-for="item in manageList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </el-form>
      </el-col>
  </div>
</template>
<style>
  .el-main{
    /* padding: 0!important; */
  }
  .row {
    /* padding-bottom: 60px!important; */
  }
</style>
<style scoped>
	.el-card.is-always-shadow {
		box-shadow: 0 0 6px 0 rgba(0,0,0,.1)!important;
	}
  .config {
    font-size: 14px;
    color: #333;
  }
  .config > .el-col-12 {
    padding: 10px;
  }
  .box-left,.box-right {
    overflow: auto;
    cursor: pointer;
  }
	.header{
		margin-bottom:20px;
	}
  .header button {
    padding: 8px 36px;
  }
  .header span {
    float: right;
  }
  .content-card {
    margin-bottom: 25px;
    background: #fafafa;
  }
  .content-card >>> .el-card__body {
    padding-top: 0;
    padding-bottom: 18px;
  }
  .content-card .el-row {
    margin-top: 18px;
  }
  .action {
    cursor: pointer;
    float: right;
  }
  .el-dropdown-link {
    color: #409eff;
  }
  /* alert */
  .alert-card {
    z-index: 2;
    position: absolute;
    top: 66px;
    right: 0;
    min-width: 580px;
    overflow: auto;
  }
  .alert-card >>> .el-card .el-card__body {
    padding: 0;
  }
  .card_header {
    margin-bottom: 10px;
    padding: 50px 30px 0px;
  }
  .card_header span {
    float: left;
    font-weight: bold;
  }
  .card_header .card_header_btn {
    float: right;
  }
  .card_header_btn button {
    float: right;
    margin-left: 20px;
    padding: 8px 16px;
  }
  .address >>> .el-form-item__error {
    top: 38px;
  }
  .item > p{
    margin: 0;
    font-size: 14px;
    padding: 16px 30px;
    background: #f5f7fa;
    font-weight: bold;
  }
  .item .el-col {
    padding: 15px 30px;
  }
  .item .el-col-8 {
    padding: 0 8px 16px 0;
  }
  .item .el-col .el-form-item {
    margin-bottom: 0;
  }
  .describe {
    position: absolute;
    top: 0;
    right: -90px;
  }
	.cr-time{
		text-align: right;
		margin:0;
		padding-bottom:10px;
	}
	.setHeight{
		height:calc(100vh - 68px);
	}
</style>

<script>
import { companyList, sectionList, addCompany, addSection, getProv, getCounty, getManage, deleteCompany, getDetail, updateCompany, updateSection } from '@/api/hr.js'

export default {
  data() {
    var checkAddress = (rule, value, callback) => {
      if (value.prov === '') {
        callback(new Error('请选择省市区'))
      } else if (value.city === '') {
        callback(new Error('请选择省市区'))
      } else if (value.county === '') {
        callback(new Error('请选择省市区'))
      } else {
        callback()
      }
    }
    var checkSimple = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入公司简称'))
      } else if (value.length > 4 || value.length < 2) {
        callback(new Error('长度在 2 到 4 个字符'))
      } else if (!(/^[a-zA-Z]+$/.test(value))) {
        callback(new Error('请输入英文'))
      } else {
        callback()
      }
    }
    var checkSection = (rule, value, callback) => {
      if (this.alertFlag === 'company') {
        callback()
      }
      if (this.alertFlag === 'section') {
        if (value === '') {
          callback(new Error('请输入部门名称'))
        } else {
          callback()
        }
      }
    }
    return {
      winHeight: '',
      headerHeight: '',
      PADDING: '', // card padding外边距
      sectionShow: false,
      companyArr: [],
      sectionArr: [],
      companyId: '',
      addAlert: false, // 添加弹窗
      companyFrom: false,
      sectionFrom: false,
      alertTitle: '',
      alertFlag: '', // 弹窗判断公司还是部门
      selectLoading: false,
      manageList: [],
      city: {
        prov: [],
        city: [],
        county: []
      },
      form: {
        cname: '',
        cid: '',
        sname: '',
        sid: '',
        simple: '',
        address: {
          prov: '',
          city: '',
          county: ''
        },
        detail: '',
        manage: null,
        manage_id: ''
      },
      rules: {
        cname: [
          { required: true, message: '请输入公司名称', trigger: 'blur' },
          { min: 1, max: 30, message: '长度在 30 个字符以内', trigger: 'blur' }
        ],
        sname: [
          { required: true, validator: checkSection, trigger: 'blur' }
        ],
        simple: [
          { required: true, validator: checkSimple, trigger: 'blur' }
        ],
        address: [
          { required: true, validator: checkAddress, trigger: 'blur' }
        ],
        detail: [
          { required: true, message: '请输入详细地址', trigger: 'blur' },
          { min: 1, max: 30, message: '长度 30 个字符以内', trigger: 'blur' }
        ],
        manage: [
          { required: false, message: '请输入负责人', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.companyList()
    this.getProvList()
  },
  methods: {
    showSection(id) {
      this.sectionShow = true
      this.companyId = id
      sectionList({company_id: id}).then((response) => {
        this.sectionArr = response.data.data
      })
      setTimeout(() => {
        const boxHeight = this.winHeight - this.headerHeight - this.PADDING
        document.querySelector('.box-right').style.height = boxHeight + 'px'
        document.querySelector('.box-right').style.maxHeight = boxHeight + 'px'
      }, 0)
    },
    alertShow(e) {
      this.alertFlag = e
      this.addAlert = true
      if (e === 'company') {
        this.alertTitle = '添加新公司'
        this.companyFrom = true
        this.sectionFrom = false
      }
      if (e === 'section') {
        this.alertTitle = '添加新部门'
        this.companyFrom = false
        this.sectionFrom = true
      }
			this.form = {
				cname: '',
				cid: '',
				sname: '',
				sid: '',
				simple: '',
				address: {
					prov: '',
					city: '',
					county: ''
				},
				detail: '',
				manage: null,
				manage_id: ''
			}
      setTimeout(() => {
        /* document.querySelector('.setHeight').style.height = this.winHeight - this.headerHeight + 'px'
        document.querySelector('.setHeight').style.maxHeight = this.winHeight - this.headerHeight + 'px' */
      }, 0)
    },
    companyList() {
      companyList().then((response) => {
        this.companyArr = response.data.data
      })
    },
    saveBtn() {
      if (this.alertFlag === 'company') {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            let params = {
              company_name: this.form.cname.trim(),
              short_name: this.form.simple,
              first_address: this.form.address.prov,
              second_address: this.form.address.city,
              third_address: this.form.address.county,
              detail_address: this.form.detail
            }
            if (this.form.manage) {
              params.company_leader = this.form.manage
            }
            if (this.alertTitle === '编辑公司') {
              params.company_id = this.form.cid
              params.company_id = this.form.cid
              params.company_leader = this.form.manage

              updateCompany(params).then((response) => {
                if (response.code !== '205') {
                  this.addAlert = false
                  this.companyList()
                }
              })
            } else {
              addCompany(params).then((response) => {
                if (response.code !== '205') {
                  this.addAlert = false
                  this.companyList()
									this.form = {
										cname: '',
											cid: '',
											sname: '',
											sid: '',
											simple: '',
											address: {
											prov: '',
												city: '',
												county: ''
										},
										detail: '',
											manage: null,
											manage_id: ''
									}
                }
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
      if (this.alertFlag === 'section') {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            let params = {
              company_id: this.companyId,
              department_name: this.form.sname.trim()
            }
            if (this.form.manage) {
              params.department_leader = this.form.manage
            }
            if (this.alertTitle === '编辑部门') {
              params.department_id = this.form.sid
              params.department_leader = this.form.manage
              updateSection(params).then((response) => {
                if (response.code !== '205') {
                  this.addAlert = false
                  this.form.sname = ''
                  this.showSection(this.companyId)
                }
              })
            } else {
              addSection(params).then((response) => {
                if (response.code !== '205') {
                  this.addAlert = false
                  this.form.sname = ''
                  this.showSection(this.companyId)
                }
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    },
    cancel() {
     /* this.city.prov = []
      this.city.city = []
      this.city.county = [] */
      this.form.sname = ''
      this.form.address.prov = ''
      this.form.address.city = ''
      this.form.address.county = ''
      this.addAlert = false
      this.companyFrom = false
      this.sectionFrom = false
      this.$refs['form'].resetFields()
    },
    companyCommand(command) {
      const every = command.substr(0, 1)
      const id = command.substr(1)
      if (every === 'a') {
        getDetail({company_id: id}).then((response) => {
          const data = response.data.data[0]
          this.getCityList(String(data.first_address), 'default')
          this.getCountyList(String(data.second_address), 'default')
          this.form.cname = data.company_name
          this.form.cid = data.id
          this.form.simple = data.short_name
          this.form.address.prov = String(data.first_address)
          this.form.address.city = String(data.second_address)
          this.form.address.county = String(data.third_address)
          this.form.detail = data.detail_address
          this.form.manage = data.company_leader
          this.form.manage_id = String(data.company_leader)
					this.manageList = [{value: data.company_leader, label: data.company_leader_text}]
        })
        this.addAlert = true
        this.companyFrom = true
				this.sectionFrom = false
        this.alertFlag = 'company'
        this.alertTitle = '编辑公司'
        setTimeout(() => {
         /* document.querySelector('.setHeight').style.height = this.winHeight - this.headerHeight + 'px'
          document.querySelector('.setHeight').style.maxHeight = this.winHeight - this.headerHeight + 'px' */
        }, 0)
      }
      if (every === 'b') {
				this.$confirm('此操作将永久删除该公司, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					deleteCompany({company_id: id}).then((response) => {
						if (response.status === 200) {
							this.$message({
								type: 'success',
								message: '删除成功'
							})
							this.companyList()
						}
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					})
				})
      }
    },
    sectioneCommand(command) {
      const every = command.substr(0, 1)
      const id = command.substr(1)
      if (every === 'a') {
        this.addAlert = true
        this.sectionFrom = true
				this.companyFrom = false
        this.alertFlag = 'section'
        this.alertTitle = '编辑部门'
        setTimeout(() => {
          /* document.querySelector('.setHeight').style.height = this.winHeight - this.headerHeight + 'px'
          document.querySelector('.setHeight').style.maxHeight = this.winHeight - this.headerHeight + 'px' */
        }, 0)
        getDetail({department_id: id}).then((response) => {
          const data = response.data.data[0]
          this.form.sname = data.department_name
          this.form.sid = id
          this.form.manage = data.department_leader
          /* this.form.manage = data.department_leader_text */
          this.form.manage_id = String(data.department_leader)
					this.manageList = [{value: data.department_leader, label: data.department_leader_text}]
        })
      }
      if (every === 'b') {
				this.$confirm('此操作将永久删除该部门, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					deleteCompany({department_id: id}).then((response) => {
						if (response.status === 200) {
							this.$message({
								type: 'success',
								message: '删除成功'
							})
							this.showSection(this.companyId)
						}
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					})
				})
      }
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          getManage({kw: query}).then((response) => {
            this.manageList = response.data.map(item => {
              return { value: item.id, label: item.username }
            })
          })
        }, 200)
      } else {
        this.manageList = []
      }
    },
    getProvList() {
      getProv().then((response) => {
				for (let item in response.data) {
					this.city.prov.splice(item, 0, response.data[item])
				}
//        response.data.forEach((item, index) => {
//          this.city.prov.splice(index, 0, item)
//        })
      })
    },
    getCityList(id, flag) {
			this.city.city = []
      // 清空市区 flag判断是change事件还是编辑弹窗
      if (flag !== 'default') {
        this.form.address.city = ''
        this.form.address.county = ''
        this.city.city = []
        this.city.county = []
      }
      getCounty({parent_id: id}).then((respone) => {
        respone.data.forEach((item, index) => {
          this.city.city.splice(index, 0, item)
        })
      })
    },
    getCountyList(id, flag) {
			this.city.county = []
      // 清空区
      if (flag !== 'default') {
        this.city.county = []
        this.form.address.county = ''
      }
      getCounty({parent_id: id}).then((respone) => {
        respone.data.forEach((item, index) => {
          this.city.county.splice(index, 0, item)
        })
      })
    }
  },
  mounted() {
    this.winHeight = document.body.clientHeight
    this.headerHeight = document.querySelector('.headerHeight').offsetHeight
    this.PADDING = 110 // card padding外边距
    const boxHeight = this.winHeight - this.headerHeight - this.PADDING
    document.querySelector('.box-left').style.height = boxHeight + 'px'
    document.querySelector('.box-left').style.maxHeight = boxHeight + 'px'
  }
}
</script>
